import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { VersioningType, VERSION_NEUTRAL } from '@nestjs/common';

import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { AllExceptionsFilter } from './common/filters/any-exception.filter';
import { ValidatePipe } from './common/pipes/validation.pipe';
import { RolesGuard } from './common/guards/roles.guard';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';

async function bootstrap() {
  // 创建应用程序实例，此时所有被 AppModule 导入的其他模块的所有实例都会被加载
  const app = await NestFactory.create(AppModule);
  const config = app.get(ConfigService);

  // 全局注册通用验证管道 ValidationPipe
  // app.useGlobalPipes(new ValidatePipe());

  // 全局注册通用异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalFilters(new AllExceptionsFilter());

  // 全局注册权限验证守卫
  // app.useGlobalGuards(new RolesGuard());

  // 全局注册响应拦截器
  // app.useGlobalInterceptors(new ResponseInterceptor());

  // 启用跨域
  app.enableCors({
    origin: config.get('cors.origin'),
    credentials: config.get('cors.credentials'),
  });

  // api 版本管理， 通过 http 来判断
  // Accept: application/json;version=2
  app.enableVersioning({
    type: VersioningType.MEDIA_TYPE,
    key: 'version=',
    defaultVersion: VERSION_NEUTRAL,
  });
  await app.listen(config.get<number>('listenPort', 3300));
}
bootstrap();
